import os
import json

def extract_and_save_code(json_dir, output_dir):
    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # Iterate through all files in the JSON directory
    for filename in os.listdir(json_dir):
        if filename.endswith(".json"):
            json_path = os.path.join(json_dir, filename)
            
            # Read and parse the JSON file
            with open(json_path, 'r', encoding='utf-8') as json_file:
                data = json.load(json_file)
                func_code = data.get("func", "")
                idx = data.get("idx", "")

                # Create the output .cpp file name
                output_filename = f"{os.path.splitext(filename)[0]}_{idx}.cpp"
                output_path = os.path.join(output_dir, output_filename)

                # Write the code to the .cpp file
                with open(output_path, 'w', encoding='utf-8') as cpp_file:
                    cpp_file.write(func_code)

# Example usage
json_directory = "/disk0/wyf/Project/zz_static_project/dataset/CodeXGLUE_Code-Code_Clone-detection-BigCloneBench"
output_directory = "/disk0/wyf/Project/zz_static_project/dataset/CodeXGLUE_Code-Code_Clone-detection-BigCloneBench_code"
extract_and_save_code(json_directory, output_directory)